import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:word_range_client/pojo/Result.dart';
import 'package:word_range_client/pojo/vo/WordMappingVo.dart';
import 'package:word_range_client/viewModels/WordBookViewModel.dart';

/// 主页的每日一词

class WordOfDay extends StatefulWidget {
  const WordOfDay({
    super.key,
    this.size = 45
  });

  final double size;

  @override
  State<WordOfDay> createState() => _WordOfDayState();
}

class _WordOfDayState extends State<WordOfDay> {
  String word = "Loading";
  String translate = "加载中";
  String lastUpdateDate = "";

  @override
  void initState() {
    super.initState();
    loadCachedWord();
  }

  void loadCachedWord() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? cachedWord = prefs.getString('cachedWordOfDayWord');
    String? cachedTranslate = prefs.getString('cachedWordOfDayTranslate');
    String? cachedDate = prefs.getString('cachedWordOfDayDate');

    if (cachedWord != null && cachedTranslate != null && cachedDate != null) {
      setState(() {
        word = cachedWord;
        translate = cachedTranslate;
        lastUpdateDate = cachedDate;
      });

      if (cachedDate != getDate()) {
        getWordOfDay();
      }
    } else {
      getWordOfDay();
    }
  }

  void getWordOfDay() async {
    WordBookViewModel wordBookViewModel = WordBookViewModel();
    Result result = await wordBookViewModel.getRandomWordByDay();
    if(result.code == 1){
      WordMappingVo wordMappingVo = WordMappingVo.fromJson(result.data!);
      setState(() {
        word = wordMappingVo.word!;
        translate = wordMappingVo.tran!;
        lastUpdateDate = getDate();
      });

      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('cachedWordOfDayWord', word);
      prefs.setString('cachedWordOfDayTranslate', translate);
      prefs.setString('cachedWordOfDayDate', lastUpdateDate);
    }
  }

  String getDate(){
    var year = DateTime.now().year;
    var month = DateTime.now().month;
    var day = DateTime.now().day;
    return "$year-$month-$day";
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: MediaQuery.of(context).size.height / 3 - 50,
      width: 550,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            word,
            style: TextStyle(fontSize: widget.size, fontWeight: FontWeight.w500),
          ),
          Text(
            translate,
            style: TextStyle(fontSize: widget.size - 20 , fontWeight: FontWeight.w300),
          ),
          Text(
            lastUpdateDate,
            style: TextStyle(fontSize: widget.size - 35, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }
}